package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lcheng.model.*;
import net.lcheng.service.*;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.vo.UserBankcardModel;
import net.lcheng.vo.UserWithdrawalsRecordModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by zwr on 2016/7/23 0023.
 */
@Controller
public class UserWithdrawalsRecordController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAccountDetailsService userAccountDetailsService;
    @Autowired
    private UserWithdrawalsRecordService userWithdrawalsRecordService;
    @Autowired
    private UserBankcardService userBankcardService;
    @Autowired
    private BaseAreasService baseAreasService;
    /**提现申请Get*/
    @RequestMapping(value = "user/withdraw")
    public String userWithdrawGet(Model model) {
        //获取当前用户
        Subject currentUser= SecurityUtils.getSubject();
        //判断当前用户有没有登录
        if(currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user=userService.getUserByUserId(currentUserModel.getUserId());
            model.addAttribute("user",user);
        }
        return "user_withdraw";
    }
 /**选择银行卡*/
    @RequestMapping(value = "select/bankcard", method = RequestMethod.GET)
    public String UserBankcardGet(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
             CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            String userId = currentUserModel.getUserId();
            User user = userService.getUserByUserId(userId);
             //获取银行卡列表
             List<UserBankcard> userBankcardList = userBankcardService.getBankcardByUserId(user.getUserId());
             //把银行卡号码用****表示
            for (int i = 0; i < userBankcardList.size(); i++) {
                String userCardNo = userBankcardList.get(i).getCardNo();
                if (userCardNo!=null&&userCardNo.length() == 16) {
                    String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "***** **** ****" + userCardNo.substring(12);
                    userBankcardList.get(i).setCardNo(cardNo);
                }
                //把银行卡号码用****表示
                if (userCardNo!=null&&userCardNo.length() == 19) {
                    String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "***** **** ****" + userCardNo.substring(15);
                    userBankcardList.get(i).setCardNo(cardNo);
                }
            }
            model.addAttribute("userBankcardList",userBankcardList);
        }
        return "my/bankcard";
    }
    /**添加银行卡get*/
    @RequestMapping(value = "/adding_bank_card", method = RequestMethod.GET)
    public String addUserBankcardGet(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            String userId = currentUserModel.getUserId();
            model.addAttribute("UserBankcardModel",new UserBankcardModel());
        }else{
            return "redirect:/login";
        }
        return "my/adding_bank_card";
    }
    /**添加银行卡post*/
    @RequestMapping(value = "/adding_bank_card", method = RequestMethod.POST)
    public String addUserBankcardPost(Model model,@Valid @ModelAttribute("UserBankcardModel") UserBankcardModel userBankcardModel, BindingResult result) {
        Subject currentUser = SecurityUtils.getSubject();
        //获取当前用户
        Session session = currentUser.getSession();
        CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
        String userId = currentUserModel.getUserId();
        User user=userService.getUserByUserId(userId);
        if (result.hasErrors()) {
            return "my/adding_bank_card";
        }
        /**获取省名称*/
        BaseAreas provinceCode = baseAreasService.getAreaCodeByAreaName(userBankcardModel.getAddrProvinceCode());
        /**获取市名称*/
        BaseAreas cityCode = baseAreasService.getAreaCodeByAreaName(userBankcardModel.getAddrCityCode());
        UserBankcard userBankcard=new UserBankcard();
        userBankcard.setBankcardId(UUID.randomUUID().toString());
        userBankcard.setUserId(userId);
        userBankcard.setUserName(user.getUserName());
        userBankcard.setAccountName(userBankcardModel.getAccountName());//开户名
        userBankcard.setBank(userBankcardModel.getBank());//开户银行
        userBankcard.setBranch(userBankcardModel.getBranch());
        userBankcard.setAddrProvinceCode(userBankcardModel.getAddrProvinceCode());//开户省编码
        userBankcard.setAddrProvinceName(provinceCode.getAreaName());
        userBankcard.setAddrCityCode(userBankcardModel.getAddrCityCode());//开户市编码
        userBankcard.setAddrCityName(cityCode.getAreaName());
        userBankcard.setCardNo(userBankcardModel.getCardNo());//银行卡
        userBankcard.setCreationTime(new Date());
        int returnResult= userBankcardService.addBakcard(userBankcard);
        if (returnResult>0){
            model.addAttribute("error", "添加成功");
            return "redirect:/select/bankcard";
        } else model.addAttribute("error", "系统异常");
        return "redirect:/adding_bank_card";
    }
    /**选择银行卡后跳转的页面*/
    /**提现申请Get*/
    @RequestMapping(value = "withdraw")
    public String withdrawGet(Model model,@RequestParam("bankcardId") String bankcardId) {
        //获取当前用户
        Subject currentUser= SecurityUtils.getSubject();
        //判断当前用户有没有登录
        if(currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user=userService.getUserByUserId(currentUserModel.getUserId());
            //判断userid和银行卡id不能为空
            if (user!=null&&bankcardId!=null){
                model.addAttribute("user",user);
                //获取银行卡信息
              UserBankcard userBankcard=userBankcardService.getUserBankcardByBankcardId(bankcardId);
                model.addAttribute("userBankcard",userBankcard);
                //初始化银行卡
                String userCardNo = userBankcard.getCardNo();
                 //判断银行卡的数字是不是16位如果是就用**表示
                if (userCardNo.length() == 16) {
                    String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "" + userCardNo.substring(12);
                   model.addAttribute("cardNo",cardNo);
                }
                //把银行卡号码用****表示
                if (userCardNo.length() == 19) {
                    String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "" + userCardNo.substring(15);
                    model.addAttribute("cardNo",cardNo);
                }
                //把userBankcard的参数传到userWithdrawalsRecordModel里面
                UserWithdrawalsRecordModel userWithdrawalsRecordModel=new UserWithdrawalsRecordModel();
                userWithdrawalsRecordModel.setUserId(user.getUserId());
                userWithdrawalsRecordModel.setUserName(user.getUserName());
                userWithdrawalsRecordModel.setAccountName(userBankcard.getAccountName());
                userWithdrawalsRecordModel.setBranch(userBankcard.getBranch());
                userWithdrawalsRecordModel.setAddrProvinceCode(userBankcard.getAddrProvinceCode());
                userWithdrawalsRecordModel.setAddrCityCode(userBankcard.getAddrCityCode());
                userWithdrawalsRecordModel.setBank(userBankcard.getBank());
                userWithdrawalsRecordModel.setCardNo(userBankcard.getCardNo());
                model.addAttribute("UserWithdrawalsRecordModel",userWithdrawalsRecordModel);
            }
        }else{
            return "redirect:/login";
        }
        return "withdraw";
    }

    /**提现申请Post*/
    @RequestMapping(value = "withdraw", method = RequestMethod.POST)
    public String userWithdrawPoser(Model model, @Valid @ModelAttribute("UserWithdrawalsRecordModel") UserWithdrawalsRecordModel userWithdrawalsRecordModel, BindingResult result) {
        //获取当前注释
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
        //获取user
        User user = userService.getUserByUserId(currentUserModel.getUserId());
        if (result.hasErrors()) {
            //初始化银行卡号码
            String userCardNo = userWithdrawalsRecordModel.getCardNo();
            //判断银行卡的数字是不是16位如果是就用**表示
            if (userCardNo.length() == 16) {
                String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "" + userCardNo.substring(12);
                model.addAttribute("cardNo", cardNo);
            }
            //把银行卡号码用****表示
            if (userCardNo.length() == 19) {
                String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "" + userCardNo.substring(15);
                model.addAttribute("cardNo", cardNo);
            }
            model.addAttribute("user", user);
            return "withdraw";
        }
        //添加提现记录
        UserWithdrawalsRecord userWithdrawalsRecord = new UserWithdrawalsRecord();
        String cashWithdrawalAmountString = userWithdrawalsRecordModel.getCashWithdrawalAmount();
        /**String类型转换为BigDecimal类型*/
        BigDecimal cashWithdrawalAmountBigDecimal = new BigDecimal(cashWithdrawalAmountString);
           //当前用户提现的金额和总金额对比不能大于总金额
        int i = cashWithdrawalAmountBigDecimal.compareTo(user.getAccountBalance());
        //BigDecimal判断-1表示小于,0是等于,1是大于.判断他提现金额不能大于总金额
        if (i == 1) {
            result.rejectValue("cashWithdrawalAmount", "misFormat", "你的提现金额大于总金额");//这个函数有好几个重载的变体
            model.addAttribute("error", "你的提现金额大于总金额");
            //初始哈银行卡号码
            String userCardNo = userWithdrawalsRecordModel.getCardNo();
            //判断银行卡的数字是不是16位如果是就用**表示
            if (userCardNo.length() == 16) {
                String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "" + userCardNo.substring(12);
                model.addAttribute("cardNo", cardNo);
            }
            //把银行卡号码用****表示
            if (userCardNo.length() == 19) {
                String cardNo = userCardNo.substring(0, userCardNo.length() - (userCardNo.substring(0)).length()) + "" + userCardNo.substring(15);
                model.addAttribute("cardNo", cardNo);
            }
            model.addAttribute("user", user);
            return "withdraw";
        } else if (i == 0 || i == -1) {
            //提现的金额和user金额相减
            double userAccountBalanceDouble= user.getAccountBalance().subtract(cashWithdrawalAmountBigDecimal).doubleValue();
            BigDecimal balance = new BigDecimal(Double.toString(userAccountBalanceDouble));
            /**获取省名称*/
            BaseAreas provinceCode = baseAreasService.getAreaCodeByAreaName(userWithdrawalsRecordModel.getAddrProvinceCode());
            /**获取市名称*/
            BaseAreas cityCode = baseAreasService.getAreaCodeByAreaName(userWithdrawalsRecordModel.getAddrCityCode());
            //添加账号明细
            UserAccountDetails userWalletDetail = new UserAccountDetails();
            userWithdrawalsRecord.setId(UUID.randomUUID().toString());
            userWithdrawalsRecord.setUserId(user.getUserId());
            userWithdrawalsRecord.setUserName(user.getUserName());
            userWithdrawalsRecord.setCashWithdrawalAmount(cashWithdrawalAmountBigDecimal);//提现金额
            userWithdrawalsRecord.setAccountName(userWithdrawalsRecordModel.getAccountName());//开户名
            userWithdrawalsRecord.setBank(userWithdrawalsRecordModel.getBank());//开户银行
            userWithdrawalsRecord.setAddrProvinceCode(userWithdrawalsRecordModel.getAddrProvinceCode());//开户省编码
            userWithdrawalsRecord.setAddrProvinceName(provinceCode.getAreaName());//开户省
            userWithdrawalsRecord.setAddrCityCode(userWithdrawalsRecordModel.getAddrCityCode());//开户市编码
            userWithdrawalsRecord.setAddrCityName(cityCode.getAreaName());//开户市
            userWithdrawalsRecord.setBranch(userWithdrawalsRecordModel.getBranch());//开户支行
            userWithdrawalsRecord.setCardNo(userWithdrawalsRecordModel.getCardNo());
            userWithdrawalsRecord.setCreateOn(new Date());
            userWithdrawalsRecord.setStatus(0);
            userWithdrawalsRecord.setAccountBalance(balance);
            int returnResult = userWithdrawalsRecordService.addWithdrawalsRecord(userWithdrawalsRecord);
            /**添加提现记录详情*/
            userWalletDetail.setWalletId(UUID.randomUUID().toString());
            userWalletDetail.setUserWithdrawalsId(userWithdrawalsRecord.getId());
            userWalletDetail.setUserId(user.getUserId());
            userWalletDetail.setUserName(user.getUserName());
            userWalletDetail.setExpenditure(cashWithdrawalAmountBigDecimal);
            userWalletDetail.setType(2);
            userWalletDetail.setCreateOn(new Date());
            userWalletDetail.setStatus(0);
            userWalletDetail.setBalance(balance);//余额
            int withdrawals = userAccountDetailsService.addUserAccountDetails(userWalletDetail);
            //更新User表里面的余额
            userService.updateAccountBalance(user.getUserId(), balance);
            if (returnResult > 0 && withdrawals > 0) {
                return "redirect:/user/withdrawals_record";
            }
            return "withdraw";
        }
        return "withdraw";
    }
}
